package com.xaicode.learn.nio;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * edit file in direct-memory, no need to copy first
 *
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/13 0013 2:27
 */
public class MappedByteBuffer01 {

    private static final String FILE_PATH = "logs" + File.separator;
    private static final String FILE_IN = FILE_PATH + "NIOFileChannel01.txt";

    public static void main(String[] args) throws IOException {

        /*
        "r"
            Open for reading only.
            Invoking any of the write methods of the resulting object will cause
            an IOException to be thrown.
        "rw"
            Open for reading and writing.
            If the file does not already exist then an attempt will be made to create it.
        "rws"
            Open for reading and writing, as with "rw",
            and also require that every update to the file's content or metadata
            be written synchronously to the underlying storage device.
        "rwd"
            Open for reading and writing, as with "rw",
            and also require that every update to the file's content
            be written synchronously to the underlying storage device.
         */
        // access file mode is one of r/rw/rws/rwd
        final RandomAccessFile accessFile = new RandomAccessFile(FILE_IN, "rw");

        // get channel
        final FileChannel channel = accessFile.getChannel();

        /*
        Maps a region of this channel's file directly into memory.

        mode – One of the constants READ_ONLY, READ_WRITE, or PRIVATE defined in the FileChannel.MapMode class,
            according to whether the file is to be mapped read-only, read/write, or privately (copy-on-write), respectively
        position – The position within the file at which the mapped region is to start;
            must be non-negative
        size – The size of the region to be mapped;
            must be non-negative and no greater than Integer.MAX_VALUE
         */
        final MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5);

        // update buffer (DirectByteBuffer)
        // check in file explorer
        mappedByteBuffer.put(0, (byte) 'M');

        channel.close();
        accessFile.close();
    }

}
